#!/bin/bash

function site_unpack() {
	echo "Unpacking site $SITENAME using platform $PLATFORM"

	rm -rf $UNPACKED
	mkdir $UNPACKED
	cd $UNPACKED
	tar zfx $SITEEXPORT
}

function db_import() {
	OUTDIR=/vagrant/output/drush
	if [ ! -d $OUTDIR ]
	then
		mkdir -p $OUTDIR
	fi
	
	echo "Importing database"
	cd $UNPACKED
	drush -y sql-create --db-su=conimbo --db-su-pw=conimbo > $OUTDIR/$SITENAME-create.log 2>&1
	drush -y sql-cli < database.sql > $OUTDIR/$SITENAME-import.log 2>&1

	echo "Clearing all caches"
	drush cache-clear all > $OUTDIR/$SITENAME-clear.log 2>&1
}

function site_etchost() {
	echo "Adding site to /etc/hosts"
	ENTRY="127.0.0.1 $SITENAME"
	ENTRYESCAPED=`echo  $ENTRY | sed "s/\./\\\\./g"`
	sed -i "/$ENTRYESCAPED/d" /etc/hosts
	echo $ENTRY >> /etc/hosts
}

function site_vhosts() {
	echo "Adding apache vhost and ssl"
	CONFPLAIN="/etc/apache2/sites-available/$SITENAME"
	CONFSSL="$CONFPLAIN-ssl"
	cp /vagrant/data/apache-vhost $CONFPLAIN
	cp /vagrant/data/apache-vhost-ssl $CONFSSL

	for CONF in $CONFPLAIN $CONFSSL
	do
		sed -i "s/PLATFORM/$PLATFORM/g" $CONF
		sed -i "s/SERVERNAME/$SITENAME/g" $CONF
		sed -i "s/SERVERALIAS/$SITENAME/g" $CONF
	done

	a2ensite $SITENAME
	a2ensite $SITENAME-ssl
}


if [ $# -eq 3 ]
then
	SITENAME=$1
	SITEEXPORT=$2
	PLATFORM=$3
	
	if [ ! -d /var/www/$PLATFORM ]
	then
		echo "Platform not found"
		exit 1
	fi
	
	UNPACKED=/var/www/$PLATFORM/sites/$SITENAME
	
	site_unpack
	db_import
	site_etchost
	site_vhosts
else
	echo "Usage: site_prepare.sh <fqdn_site> <export_file_location.tgz> <platform_name>"
	exit -1
fi
